package com.lagou.edu.lagouserviceemail.service.impl;

import com.lagou.edu.EmailService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * All rights Reserved, Designed By qinmp.
 *
 * @author: qinmp
 * @date:2020-09-20 13:42
 * @copyright:
 */
@Service
public class EmailServiceImpl implements EmailService, InitializingBean {

    Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    Map<String, Long> sendRecordMap = new ConcurrentHashMap<>();

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>());

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Override
    public boolean sendRandomCodeEMail(String email, String code) {

        Long preTime = sendRecordMap.get(email);
        if(null != preTime){
            Long currentTime = System.currentTimeMillis();
            if ((currentTime - preTime) <= 60*1000) {
                logger.info("一分钟只允许获取一次验证码");
                return false;
            }
        }
        sendRecordMap.put(email, System.currentTimeMillis());
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("邮箱验证码");
        message.setText("您发送的登录验证码是：" + code);
        message.setTo(email);
        message.setFrom("18684048891@163.com");
        threadPoolExecutor.execute(()->{
            javaMailSender.send(message);
        });
        logger.info("=============邮件发送完成=============");
        return true;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
    }
}
